const express = require('express')
const { Mongoose } = require('mongoose')
const router = express.Router()

const { CartModel } = require('../model/index')

router.post('/storecart', (req, res) => {
  const { username, cart } = req.body
  CartModel.find({ username }, (err, data) => {
    if (err) {
      res.json({
        code: 500,
        data: err
      })
    } else {
      CartModel.deleteMany({ username }, (err, data) => {
        if (err) {
          res.json({
            code: 500,
            data: err
          })
        } else {
          new CartModel({ username, cart }).save()
            .then(resp => {
              res.json({
                code: 200,
                data: resp
              })
            }).catch(err => {
              res.json({
                code: 400,
                data: err
              })
            })
        }
      })
    }
  })
  // new CartModel({ username, cart }).save()
  //   .then(resp => {
  //     res.json({
  //       code: 200,
  //       data: resp
  //     })
  //   }).catch(err => {
  //     res.json({
  //       code: 400,
  //       data: err
  //     })
  //   })
})

router.post('/getcart', (req, res) => {
  const { username } = req.body
  CartModel.find({ username }, (err, data) => {
    console.log(data)
    res.json({
      code: 200,
      data: data[0].cart
    })
  })
})

module.exports = router